package com.hulk.boot.mobile.exceptionhandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.google.common.base.Throwables;

import lombok.extern.slf4j.Slf4j;

/**
 * @author cmt
 * 
 * 
 * 
 *
 */
@Slf4j
@ControllerAdvice
public class MobileExceptionAdvice {

	@ExceptionHandler(RuntimeException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "RuntimeException occured")
	@ResponseBody
	public ExceptionResponse handleRuntimeException(HttpServletRequest request, HttpServletResponse Response,
			Exception ex) {
		String message = Throwables.getStackTraceAsString(ex);
		return new ExceptionResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
	}

	@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Exception occured")
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ExceptionResponse handleException(HttpServletRequest request, HttpServletResponse Response, Exception ex) {

		String message = Throwables.getStackTraceAsString(ex);
		return new ExceptionResponse(HttpStatus.NOT_FOUND.value(), message);
	}

	 class ExceptionResponse {

		private String message;
		private Integer code;

		
		public ExceptionResponse(Integer code, String message) {
			this.message = message;
			this.code = code;
		}

		public Integer getCode() {
			return code;
		}

		public String getMessage() {
			return message;
		}
	}

	@ModelAttribute
	public void addAttribute(Model m) {
		m.addAttribute("msg", "bye");
		log.debug("============应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		log.debug("============应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
	}
	
//	@ResponseBody
//	作用： 
//	      该注解用于将Controller的方法返回的对象，通过适当的HttpMessageConverter转换为指定格式后，写入到Response对象的body数据区。
//	使用时机：
//	      返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用；

}